package org.hot100_6.leetcode438;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    public static void main(String[] args) {
        findAnagrams("cbaebabacd","abc");
    }

    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int pLength= p.length();
        int sLength= s.length();

        if (pLength>sLength){
            return result;
        }
        char [] pChars = new char[26];
        char [] sChars = new char[26];


        for (char ch : p.toCharArray()) {
            pChars[ch-'a']++;
        }

        int left = 0;

        for (int i = 0; i < pLength; i++) {
            sChars[s.charAt(i)-'a']++;
        }

        if (Arrays.equals(pChars,sChars)){
            result.add(0);
        }

        for ( ;left < sLength-pLength; left++) {
            sChars[s.charAt(left)-'a']--;
            sChars[s.charAt(left+pLength)-'a']++;
            if (Arrays.equals(pChars,sChars)){
                result.add(left+1);
            }
        }


        return result;
    }
}
